package com.xtianzhuang.www.study2019.practice.leetcode.study.hash;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Soultion {
	public static void main(String[] args) {
		System.out.println(singleNumber(new int[]{2, 2, 1}));
	}

	/**
	 * 给定一个整数数组，判断是否存在重复元素。
	 * @param nums
	 * @return
	 */
	public boolean containsDuplicate(int[] nums) {
		Set<Integer> set = new HashSet();
		for (int i = 0; i < nums.length; i++) {
			if (set.contains(nums[i])) {
				return true;
			}
			set.add(nums[i]);
		}
		return false;
	}

	/**
	 * 给定一个非空整数数组，除了某个元素只出现一次以外，其余每个元素均出现两次。找出那个只出现了一次的元素。
	 * @param nums
	 * @return
	 */
	public static int singleNumber(int[] nums) {
		Set<Integer> set = new HashSet();
		for (int i = 0; i < nums.length; i++) {
			if (set.contains(nums[i])) {
				set.remove(nums[i]);
			} else {
				set.add(nums[i]);
			}

		}
		return set.iterator().next();
	}

	public int singleNumber2(int[] nums) {
		int temp = 0;

		for (int i : nums) {
			temp ^= i;
		}

		return temp;
	}

	public static int[] intersection(int[] nums1, int[] nums2) {
		Set<Integer> n1 = new HashSet<>();
		Set<Integer> n3 = new HashSet<>();
		for (int i = 0; i < nums1.length; i++) {
			n1.add(nums1[i]);
		}
		for (int i = 0; i < nums2.length; i++) {
			if (n1.contains(nums2[i])) {
				n3.add(nums2[i]);
			}
		}
		int[] arrays = new int[n3.size()];
		Iterator<Integer> it = n3.iterator();
		int i = 0;
		while (it.hasNext()) {
			int str = it.next();
			arrays[i] = str;
			i++;
		}
		return arrays;
	}
}
